package uprobe

import (
	"eSymCounter/config"
	"fmt"
	"log"
	"os"
	"time"
)

//go:generate go run github.com/cilium/ebpf/cmd/bpf2go bpf ../../kern/uprobe.c -- -I../../kern/headers

type Event struct {
	Symbol string
	Cnt    uint64
}

func exitAndPrintResults(resultChan <-chan Event) {

	for config.BpfProgsNum.Load() > 0 {
		fmt.Printf("\rWaiting for bpf progs to finish, %5v remaining", config.BpfProgsNum.Load())
		time.Sleep(1 * time.Second)
	}
	fmt.Printf("\rWaiting for bpf progs to finish, %5v remaining\n", 0)

	outputStream := os.Stdout
	if config.OutputFile != "" {

		file, err := os.OpenFile(config.OutputFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			log.Printf("Failed to open file: %v\n", err)
			return
		}
		defer file.Close()
		outputStream = file
	}
	fmt.Fprintf(outputStream, "Results:\n")
	for res := range resultChan {
		fmt.Fprintf(outputStream, "Symbol %v called %v times\n", res.Symbol, res.Cnt)
	}
}
